package base

import (
	. "jvm/typedef"
)

type CodeReader struct {
	code []U1
	pc   U4
}

func NewCoderReader(code []U1) *CodeReader {
	return &CodeReader{
		code: code,
		pc:   0,
	}
}
func (self *CodeReader) ReadU1() U1 {
	val := self.code[self.pc]
	self.pc++
	return val
}

// 大端读法 先读高位，再读低位
func (self *CodeReader) ReadU2() U2 {
	high := U2(self.ReadU1())
	low := U2(self.ReadU1())
	return (high << 8) | low

}

func (self *CodeReader) ReadU4() U4 {
	high := U4(self.ReadU2())
	low := U4(self.ReadU2())
	return (high << 16) | low
}
func (self *CodeReader) ReadU8() U8 {
	high := U8(self.ReadU4())
	low := U8(self.ReadU4())
	return (high << 32) | low
}

func (self *CodeReader) ReadI1() I1 {
	return I1(self.ReadU1())
}
func (self *CodeReader) ReadI2() I2 {
	return I2(self.ReadU2())
}

func (self *CodeReader) ReadI4() I4 {
	return I4(self.ReadU4())
}
func (self *CodeReader) ReadI8() I8 {
	return I8(self.ReadU8())
}

func (self *CodeReader) SkipPadding() {
	skip := 4 - (self.pc % 4)
	if skip != 4 {
		self.pc += skip
	}

}

// getter
func (self *CodeReader) PC() U4 {
	return self.pc
}

// setter
func (self *CodeReader) SetPC(pc U4) {
	self.pc = pc
}
